/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.module.repository;

import com.lap.auth.adapter.driving.persistence.module.ModuleConverter;
import com.lap.auth.adapter.driving.persistence.module.mapper.ModuleMapper;
import com.lap.auth.adapter.driving.persistence.module.po.ModulePo;
import com.lap.auth.domain.module.Module;
import com.lap.auth.domain.module.repository.ModuleRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class ModuleRepositoryImpl implements ModuleRepository {

  private final ModuleConverter moduleConverter;
  private final ModuleMapper moduleMapper;

  @Override
  public Integer save(Module module) {
    ModulePo modulePo = moduleConverter.toPo(module);
    if (module.isNew()) {
      moduleMapper.insert(modulePo);
      return modulePo.getId();
    }
    return moduleMapper.updateByPrimaryKey(modulePo);
  }

  @Override
  public int deleteById(Integer id) {
    return moduleMapper.deleteByPrimaryKey(id);
  }

  @Override
  public Optional<Module> findById(Integer id) {
    var modulePo = moduleMapper.selectByPrimaryKey(id);
    return Optional.ofNullable(moduleConverter.toDomain(modulePo));
  }

  @Override
  public Optional<Module> findByRouteId(String routeId) {
    var modulePo = moduleMapper.selectByRouteId(routeId);
    return Optional.ofNullable(moduleConverter.toDomain(modulePo));
  }
}
